<template>
	<view class="house-content">
		<!-- <view class="swiper-banner">
			<u-swiper :list="houseDetail.images" height="400"></u-swiper>
		</view> -->
		<view class="house-info">
			<view class="house-title mb20" @click="copyTitle">
				{{houseDetail.title}}
			</view>
			<view class="price-type mb20">
				<view class="house-price">
					租金:
					<text>{{houseDetail.price}}元/月</text>
				</view>
				<view class="house-type">户型：{{houseDetail.tags}}</view>
			</view>
			<view class="house-notagencyFee mb20" v-if="houseDetail.isAgency == 1">
				有中介费
			</view>
			<view class="house-agencyFee mb20" v-if="houseDetail.isAgency == 0">
				无中介费
			</view>
			<view class="house-create mb20">
				发布时间：{{houseDetail.releaseTime}}
			</view>
			<!-- <view class="house-address" @click="openMap">
				<view class="address-text">
					<u-icon name="map"></u-iscon>
					{{houseDetail.address}}
				</view>
				<view class="distance-text">
					距离约{{houseDetail.distance}}Km
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view> -->
		</view>
		<view class="house-detail">
			<!-- <view class="detail-title">
				详情描述
			</view> -->
			<!-- <view v-html="houseDetail.description"></view> -->
			<view v-if="imageList.length != 0">
				<view class="detail-item" v-for="item in houseDetail.images" :key="item">
					<image class="item-file" :src="item" mode="widthFix"></image>
				</view>
			</view>

			<view v-if="src != ''">
				<view class="detail-item">
					<video height="500rpx" :src="src" class="item-file"></video>
				</view>
			</view>


		</view>
		<view class="advert-box">
			<u-swiper :list="list" height="250" @click='clickSwiper'></u-swiper>
		</view>
		<view style="width: 100%; height: 150rpx;"></view>
		<view class="bottom-config">
			<view class="config-left">
				<!-- <view class="left-item" @click="gotoIndex">
					<u-icon name="home" size='34'></u-icon>
					<view>首页</view>
				</view> -->
				<!-- <view class="left-item" @click="collect">
					<u-icon name="star" size='34' v-if="!houseDetail.isCollect"></u-icon>
					<u-icon name="star-fill" size='34' color="rgb(255,205,0)" v-if="houseDetail.isCollect"></u-icon>
					<view>收藏</view>
				</view> -->
				<view class="left-item" v-if="src != ''" @click="downVideo">
					<u-icon name="photo-fill" size='34'></u-icon>
					<view>下载视频</view>
				</view>
				<view class="left-item" @click='shareByMoney(2)' v-if="userType != 3">
					<u-icon name="share" size='34'></u-icon>
					<view>分享</view>
				</view>
			</view>
			<view class="config-right">
				<!-- 	<view class="right-item green">
					<u-icon name="weixin-fill" size='32' color="#fff"></u-icon>
					<view>微信号</view>
				</view> -->

				<u-button type="primary" shape="circle" @click='buyShow = true' :custom-style="customStyle"
					v-if="userType != 3">预定房源</u-button>
				<u-button type="primary" open-type='share' shape="circle" @click='shareByMoney(1)'
					:custom-style="customStyle" v-if="userType == 3">分享获佣</u-button>
			</view>
		</view>
		<u-popup v-model="buyShow" mode="bottom" border-radius="14" height="800rpx" :closeable="true">
			<view class="popup-box">
				<view class="popup-info">
					<view class="info-image">
						<image :src="houseDetail.postUrl" mode=""></image>
					</view>
					<view class="info-detail">
						<view class="info-title">{{houseDetail.title}}</view>
						<view class="info-price">￥{{checkedForm.price || 0}}/月</view>
						<view>已选：{{checkedForm.title ||'无'}}</view>
					</view>
				</view>
				<view class="select-box">
					<view class="select-title">规格</view>
					<view class="tags-list">
						<view class="tags-item" :class="item.ischecked ? 'tags-checked' : ''"
							v-for="item in houseDetail.tagsList" :key="item.id" @click="checkedTags(item)">
							{{item.title}}
						</view>
					</view>
				</view>
				<view class="submit-btn">
					<u-button type="error" @click='submitBuy'>预定房源￥{{checkedForm.price || 0}}</u-button>
				</view>
			</view>
		</u-popup>
		<view class="progress-container" v-if="isShowProgress">
			<view class="progress-box">
				<view class="text">文件下载中，请稍后......</view>
				<progress :percent="progress" show-info stroke-width="3" />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		GetHouseDetail,
		GetHouseSkuInfo,
		HouseCollect,
		CreateOrder,
		GetAdvertisement
	} from "@/api/index.js"
	import {
		login
	} from "@/api/login.js"
	export default {
		data() {
			return {
				isClickDown: false,
				src: '',
				checkedForm: {},
				customStyle: {
					width: '400rpx'
				},
				buyShow: false,
				houseDetail: {},
				list: [],
				selfLocation: {
					lat: 0, //维度
					lng: 0, //经度
				},
				userType: 1,
				shareUserId: null,
				imageList: [],
				isShowProgress: false,
				progress: 0,
			}
		},
		async onLoad(op) {
			// #ifdef H5
			if (!uni.getStorageSync('Authorization')) {
				//一种是调回来带了code
				// const params = {
				// 	id:op.id,
				// 	shareUserId:op.shareUserId || ''
				// }
				const isCode = window.location.search.indexOf('?code') > -1
				let url =
					`https://aiyouzixun.top/#/pages/houseDetail/index?id=${op.id}&shareUserId=${op.shareUserId || ''}`
				if (isCode) {
					const querystring = window.location.search.slice(1)
					const urlSearchParams = new URLSearchParams(querystring)
					const code = urlSearchParams.get('code')
					//获取登录信息
					this.onWxLogin(url, code)
				} else {

					//如果说没有直接登录
					this.login(url)
				}

			}
			// #endif
			// https://aiyouzixun.top/#/pages/houseDetail/index?id=21
			this.userType = uni.getStorageSync('USER_TYPE')
			await this.getSelfLocation()
			await this.getDetail(op.id)
			await this.getAd()
			if (op.shareUserId) {
				this.shareUserId = op.shareUserId
			}
		},
		methods: {
			downVideo() {
				// this.isClickDown = true
				uni.navigateTo({
					url:'/pages/webView/index?src=' + this.src
				})
				// uni.setClipboardData({
				// 	data: this.src,
				// 	showToast: false,
				// 	success: function() {
				// 		uni.showModal({
				// 			title: '提示',
				// 			content: '请点击右上角打开浏览器，将链接粘贴在地址栏进行下载！',
				// 			success: function(res) {
				// 				if (res.confirm) {
				// 					console.log('用户点击确定');
				// 				} else if (res.cancel) {
				// 					console.log('用户点击取消');
				// 				}
				// 			}
				// 		});
				// 	},
				// 	fail: function() {
				// 		// uni.showToast({
				// 		// 	title: "复制标题失败，稍后再试",
				// 		// 	icon: "none",
				// 		// 	duration: 2000
				// 		// });
				// 	}
				// });
			},
			copyTitle() {
				uni.setClipboardData({
					data: this.houseDetail.title,
					showToast: false,
					success: function() {
						uni.showToast({
							title: "复制标题成功",
							icon: "success",
							duration: 2000
						});
					},
					fail: function() {
						uni.showToast({
							title: "复制标题失败，稍后再试",
							icon: "none",
							duration: 2000
						});
					}
				});
			},
			onWxLogin(url, code) {
				let _self = this
				// const code = _self.getUrlCode().code
				login({
					code,
				}).then(res => {
					// _self.userInfo = res.data
					uni.setStorageSync('Authorization', res.data.token)
					uni.setStorageSync("userInfo", res.data)
					uni.setStorageSync('USER_TYPE', res.data.userType)
					uni.setStorageSync('isLogin', true)
					//清除code
					window.location.href = url
				})
			},
			getUrlCode() { // 截取url中的code方法
				var url = window.location.href
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(url.indexOf('?') + 1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						var items = strs[i].split('=');
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			},
			login(local) {
				let appid = 'wx2451c4811732a3e4'
				local = encodeURIComponent(local) // 获取页面url
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect'`
			},
			clickSwiper(index) {
				window.location.href = this.list[index].link
			},
			// 获取广告
			getAd() {
				GetAdvertisement({
					type: 2
				}).then(res => {
					this.list = res.data
				})
			},
			shareByMoney(type) {
				let that = this
				let userInfo = uni.getStorageSync('userInfo')
				if (userInfo.phone == '' && userInfo.weChatSignal == '') {
					that.buyShow = false
					uni.showModal({
						title: '提示',
						content: '请完善个人信息后再分享！',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/personCenter/index'
								})
							} else if (res.cancel) {
								uni.navigateBack()
							}
						}
					})
					return
				}
				let href = ''
				if (type == 1) {
					// href =
					// 	`https://aiyouzixun.top/#/pages/houseDetail/index?id=${this.houseDetail.id}&shareUserId=${uni.getStorageSync('userInfo').openId}`
					uni.navigateTo({
						url: '/pages/shareIndex/index?id=' + that.houseDetail.id
					})
				} else {
					href =
						`https://aiyouzixun.top/#/pages/houseDetail/index?id=${this.houseDetail.id}`
					uni.setClipboardData({
						data: href,
						showToast: false,
						success: function() {
							uni.showToast({
								title: "复制成功,去转发吧",
								icon: "success",
								duration: 2000
							});
						},
						fail: function() {
							uni.showToast({
								title: "复制失败，请重新分享",
								icon: "none",
								duration: 2000
							});
						}
					});
				}
			},
			// 获取自己当前经纬度
			getSelfLocation() {
				let _self = this
				uni.getLocation({
					type: 'gcj02', // 使用国标坐标系
					isHighAccuracy: true, // 高精度定位，会调用gps获取高精度坐标
					success(res) {
						_self.selfLocation.lat = res.latitude
						_self.selfLocation.lng = res.longitude
						console.log(res, '当前位置');
					},
					fail(err) {}
				})
			},
			//进行经纬度转换为距离的计算
			Rad(d) {
				return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
			},
			// 计算两点距离
			GetDistance(lat1, lng1) {
				console.log(lat1, lng1, 'lat1, lng1');
				let _self = this
				let lat2 = _self.selfLocation.lat; //自己的维度
				let lng2 = _self.selfLocation.lng; //自己的经度
				console.log(lat2, lng2, 'lat2, lng2');
				var radLat1 = _self.Rad(lat1);
				var radLat2 = _self.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = _self.Rad(lng1) - _self.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137;
				s = Math.round(s * 10000) / 10000 / 10000;
				return s.toFixed(1);
			},
			timetrans(date, isAll = false, Y = "-", M = "-", D = " ") {
				if (!isAll) {
					D = ''
				}
				var date = parseInt(date);
				date = date.toString().length == 13 ? new Date(date) : new Date(date *
					1000); //如果date为13位不需要乘1000 
				var Y = date.getFullYear() + Y;
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + M;
				var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + D;
				if (isAll) {
					var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + '';
					var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
					var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
					return Y + M + D + h + ':' + m + ':' + s;
				} else {
					return M + D;
				}
			},
			// 打开地图
			openMap() {
				uni.openLocation({
					latitude: this.houseDetail.position[1],
					longitude: this.houseDetail.position[0],
					success: function() {
						console.log('success');
					},
					fail(error) {
						console.log(error, 'error');
					}
				});
			},
			getSkuInfo(houseId) {
				let query = {
					houseId
				}
				GetHouseSkuInfo(query).then(res => {
					res.data.forEach(ele => {
						this.$set(ele, 'ischecked', false)
					})
					this.$set(this.houseDetail, 'tagsList', res.data)
				})
			},
			getDetail(id) {
				let that = this
				let query = {
					id
				}
				// this.getSelfLocation();
				GetHouseDetail(query).then(res => {
					that.houseDetail = res.data
					// let imageList = []
					that.houseDetail.images = that.houseDetail.images.split(",")
					that.houseDetail.images.forEach(ele => {
						const extIndex = ele.lastIndexOf('.');
						const extName = ele.slice(extIndex + 1)
						if (extName == 'mp4' || extName == 'mov') {
							that.src = ele
						} else {
							that.imageList.push(ele)
							that.houseDetail.images = that.imageList
						}
					})
					that.houseDetail.position = that.houseDetail.position.split(",")
					that.houseDetail.position.forEach((ele, index) => {
						that.houseDetail.position[index] = parseFloat(that.houseDetail
							.position[index])
					})
					that.houseDetail.releaseTime = this.timetrans(that.houseDetail.releaseTime, true)
					let distance = that.GetDistance(that.houseDetail.position[1], that.houseDetail
						.position[0])
					that.$set(that.houseDetail, 'distance', distance)
					this.getSkuInfo(id)
				})
			},
			gotoIndex() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			collect() {
				let query = {
					openId: uni.getStorageSync('userInfo').openId,
					houseId: this.houseDetail.id,
					isAdd: this.houseDetail.isCollect ? 2 : 1
				}
				HouseCollect(query).then(res => {
					this.getDetail(this.houseDetail.id)
				})
			},
			checkedTags(item) {
				if (item.ischecked) {
					item.ischecked = false
					this.checkedForm = {}
					return
				}
				this.checkedForm = item
				this.houseDetail.tagsList.map(ele => {
					ele.ischecked = false
					item.ischecked = true
				})
			},
			submitBuy() {
				let that = this
				let userInfo = uni.getStorageSync('userInfo')
				if (userInfo.userType == 2) {
					uni.showToast({
						title: '房源商无法预定房源',
						icon: 'error'
					})
					return
				}
				that.buyShow = false
				if (userInfo.phone == '' && userInfo.weChatSignal == '') {
					uni.showModal({
						title: '提示',
						content: '请完善个人信息后再下单！',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/personCenter/index'
								})
							} else if (res.cancel) {
								uni.navigateBack()
							}
						}
					})
					return
				}
				if (JSON.stringify(that.checkedForm) == '{}') {
					uni.showToast({
						title: '请选择规格',
						icon: 'error'
					})
					return
				}
				let query = {
					houseId: that.houseDetail.id,
					openId: uni.getStorageSync('userInfo').openId,
					skuId: that.checkedForm.id,
					intermediaryId: that.shareUserId || '',
				}
				CreateOrder(query).then(res => {
					that.pay(res)
					// this.buyShow = false
					// uni.navigateTo({
					// 	url: '/pages/orderDetail/index'
					// })
				})

				// this.checkedForm = {}
			},
			// 支付
			pay(params) {
				WeixinJSBridge.invoke('getBrandWCPayRequest', params, res => {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						//支付成功
						// resolve(true)
						uni.navigateTo({
							url: '/pages/houseDetail/successPay?orderNo=' + params.orderNo
						})
					} else {
						//支付失败
						// resolve(false)
						uni.showToast({
							title: "支付失败！",
							icon: 'error',
							duration: 800
						})
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/orderDetail/index?orderNo=' + params
									.orderNo
							})
						}, 1000)

					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.progress-container {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		background: rgba(0, 0, 0, .2);
		width: 750rpx;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;

		.progress-box {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 30rpx;

			.text {
				margin-bottom: 20rpx;
			}
		}
	}

	.mb20 {
		margin-bottom: 20rpx;
	}

	.swiper-banner {
		width: 100%;
	}

	.house-info {
		padding: 20rpx;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		justify-content: space-around;

		.house-title {
			font-size: 32rpx;
			font-weight: bold;
		}

		.price-type {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.house-price {
				font-size: 36rpx;
				font-weight: bold;

				>text {
					color: #bf0000;
				}
			}

			.house-type {
				padding: 5rpx 10rpx;
				color: #fff;
				font-size: 26rpx;
				background-color: #1296db;
				border-radius: 10rpx;
			}

		}

		.house-agencyFee {
			padding: 5rpx 10rpx;
			color: #fff;
			font-size: 26rpx;
			background-color: #1296db;
			border-radius: 10rpx;
			width: max-content;
		}

		.house-notagencyFee {
			padding: 5rpx 10rpx;
			color: #fff;
			font-size: 26rpx;
			background-color: #aa0000;
			border-radius: 10rpx;
			width: max-content;
		}

		.house-address {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-weight: bold;
			color: rgb(83, 146, 212);
		}
	}

	.house-detail {
		margin-top: 20rpx;
		padding: 10rpx;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		>view {
			width: 100%;

			.item-file {
				width: 100%;
			}
		}



		/deep/ .uni-image {
			width: 360px !important;
		}

		// .detail-title {
		// 	text-align: center;
		// 	font-size: 32rpx;
		// 	font-weight: bold;
		// 	margin-bottom: 20rpx;
		// }
	}

	.advert-box {
		width: 100%;
		margin-top: 20rpx;
	}

	.bottom-config {
		z-index: 9999;
		position: fixed;
		bottom: 0;
		width: 100%;
		padding: 10rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		border-top: 1px solid #adadad;

		.config-left {
			font-size: 24rpx;
			width: 40%;
			display: flex;
			align-items: center;
			justify-content: space-around;

			.left-item {
				display: flex;
				flex-direction: column;
				align-items: center;
			}
		}
	}

	.config-right {
		width: 60%;
		display: flex;
		justify-content: space-around;

		.right-item {
			display: flex;
			align-items: center;
			color: #fff;
			padding: 10rpx 20rpx;
			border-radius: 50rpx;
		}

		.green {
			background-color: #44cc00;
		}

		.blue {
			background-color: #1296db;
		}
	}

	.popup-box {
		padding: 20rpx;
		position: relative;
		height: 100%;

		.popup-info {
			display: flex;

			.info-image {
				width: 180rpx;
				height: 180rpx;
				border-radius: 10rpx;
				overflow: hidden;
				margin-right: 15rpx;

				>image {
					width: 100%;
					height: 100%;
				}
			}

			.info-detail {
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.info-title {
					font-size: 32rpx;
				}

				.info-price {
					color: #bf0000;
					font-size: 32rpx;
					font-weight: bold;
				}
			}
		}

		.select-box {
			margin-top: 20rpx;

			.select-title {
				color: #cacaca;
			}

			.tags-list {
				margin-top: 10rpx;
				display: flex;
				flex-wrap: wrap;

				.tags-item {
					margin-right: 20rpx;
					border: 1rpx solid #EEE;
					border-radius: 10rpx;
					padding: 10rpx 20rpx;
					margin-bottom: 20rpx;
				}

				.tags-checked {
					color: #1296db;
					border: 1rpx solid #1296db;
					background-color: #ebfeff;
				}
			}
		}

		.submit-btn {
			position: absolute;
			bottom: 40rpx;
			left: 5%;
			width: 90%;
		}
	}
</style>